package com.huilian.tool.work.weixin.service.impl;

import com.huilian.tool.work.weixin.enums.MediaTypeEnum;
import com.huilian.tool.work.weixin.service.WorkWeiXinUploadService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;

/**
 * @Author 少凡
 * @Date 2022-07-09 19:04
 * version 1.0
 */
@Service
public class WorkWeiXinUploadServiceImpl implements WorkWeiXinUploadService {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public String uploadAttachment(String accessToken, MediaTypeEnum mediaTypeEnum, Integer attachmentType, String filePath) {

        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment?")
                .append("access_token=").append(accessToken)
                .append("&media_type=").append(mediaTypeEnum.getCode())
                .append("&attachment_type=").append(attachmentType)
                .toString();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        File file = new File(filePath);

        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", new FileSystemResource(file));
        form.add("filename",file.getName());

        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(form, headers);

        return restTemplate.postForObject(url, entity, String.class);

    }

}
